<!DOCTYPE HTML PUBLIC "f-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
	<link rel="icon" type="image/vnd.microsoft.icon" href="images/bridge.ico">
    <link type="text/css" href="styles/base/ui.all.css" rel="stylesheet" />
    <style type="text/css" media="screen">
        @import url("styles/gb.css");
		@import url("styles/autocomplete/jquery.autocomplete.css");
    </style>
    <script type="text/javascript" src="scripts/jquery.min.js "></script>
    <script type="text/javascript" src="scripts/jquery.parsequery.js" ></script>
    <script type="text/javascript" src="scripts/jquery-jtemplates.js"></script>
    <script type="text/javascript" src="scripts/jquery.corner.js"></script>
    <script type="text/javascript" src="scripts/ui/jquery-ui-1.7.2.custom.js"></script>
    <script type="text/javascript" src="scripts/ui/ui.datepicker.js"></script>
    <script type="text/javascript" src="scripts/flowplayer/flowplayer-3.1.1.min.js"></script>
    <script type="text/javascript" src="scripts/date.js"></script>
	<script type="text/javascript" src="scripts/jquery.autocomplete.min.js"></script>
	<script type="text/javascript" src="scripts/swfobject.js"></script>
	<script type="text/javascript" src="scripts/navigation.js"></script>
	<script type="text/javascript" src="scripts/player.js"></script>
	<script type="text/javascript" src="scripts/youtube_player.js"></script>
    <script type="text/javascript" src="scripts/jquery.easing.min.js"></script>
    <script type="text/javascript" src="scripts/jquery.lavalamp.min.js"></script>
	<script type="text/javascript" src="scripts/jquery.timers.js"></script>
	<script type="text/javascript" src="scripts/jquery.jeditable.mini.js"></script>
	<script type="text/javascript" src="/_utils/script/json2.js"></script>
	<script type="text/javascript" src="scripts/jquery.cookie.js"></script>
	<script type="text/javascript" src="scripts/jquery.shortkeys.js"></script>
    <script type="text/javascript">
		var player;
        var query_vars;
		var db_name;
		var conversation;
		var conversation_tags;
		var tag_id_to_row = new Array();
		var tag_to_remove;
		var twitter_id_to_tweet = new Array();
		
				
        
        var disableScrubberUpdates = false;

		
        function updateScrubber() {
			if (player == null) {
				return;
			}
            if (!disableScrubberUpdates) {
				try {
					var time = player.time();
					$("#scrubber").slider('option', 'value', time );
					updatePlayhead();
				} catch (e) {}
            }
        }
		
		
        function updatePlayhead() {
            var scrubber_offset = $('#scrubber a').offset();
            scrubber_offset.top += 18;
            var height = $('#tags_table').height();
			var external_height = $('#external_tags_table').height();
			height = height + external_height;
			height = height + "px";
            $("#playhead").css({top: scrubber_offset.top, left: scrubber_offset.left, height: height});
        }

        function windowResize() {
            updatePlayhead();
        }

        function parseAttachments(attachments) {
            var map;
            var images = new Array();
            jQuery.each(attachments, function(name, info) {
                if (name.search(".*\\.mm") != -1) {
                    map = name;
                }
                if (name.search(".*\\.(png|jpg|gif|jpeg|JPG)", "i") != -1) {
                    var image = {};
                    image.name = name;
                    images.push(image);
                }
               
            });
            if (map) showMap(map);
            showImages(images);
        }


        function showMap(name) {
            
            // attach the template
            $("#map").setTemplateElement("map_template");

            var data ={};
            data.url = "http://" + window.location.hostname + ":5984/" + db_name + "/" + query_vars.name + "/" + escape(name);
            //data.url = "map.mm";
            // process the template
            $("#map").processTemplate(data);
        }


        function showImages(images) {
            jQuery.each(images, function(i, image) {
                image.url = "/" + db_name + "/" + query_vars.name + "/" + image.name;
            });
            var data = {};
            data.images = images;
            $("#images_table").setTemplateElement("images_table_template");
            $("#images_table").processTemplate(data);
        }

		var scrubberInterval;
		
		function finishLoadingAudio() {
				$('#loading').hide();
				if (!scrubberInterval) {
					scrubberInterval = setInterval("updateScrubber()", 450);
				}
		}	

        function findRequestedStartTime() {
            var time = query_vars.time;
            if (time == null) time = 0;
            return time;
        }

        $(function() {

			$(document).shortkeys({
			  'X':       function () { player.play(); },
			  'Z':       function () { playLastTag(); },
			  'A':       function () { showAddTagDialog(); }
			  
			});	
            $(window).resize(windowResize);
			db_name = findDBName();
			$('#newTagDialog').dialog({
			    	autoOpen: false,
			    	resizable: false,
		            modal: true,
					buttons: {
						'Ok': function() {
							var mediaOffset = $('#newTagTime').val();
							var tagName = $('#newTagInput').val();
							var tagDescription = $('#newTagDescription').val();
						    addTag(tagName, mediaOffset, tagDescription )
							$(this).dialog('close');
						},
						'Cancel' : function() {
							$(this).dialog('close');
						}
					},
					close: function() {

					}
		    });
			$('#removeTagDialog').dialog({
			    	autoOpen: false,
			    	resizable: false,
		            modal: true,
					buttons: {
						'Ok': function() {
						   $(this).dialog('close');
						   var doc = {};
						   doc._id = tag_id_to_row[tag_to_remove].value._id;
						   doc._rev    = tag_id_to_row[tag_to_remove].value._rev;
						   var data = JSON.stringify(doc);
							$.ajax({
							   type: "DELETE",
							   url: "/" + db_name + "/" + doc._id + "?rev=" + doc._rev,
							   success: function(msg){
								 $('#row-' + tag_to_remove ).hide();
							   }
							});
						},
						'Cancel' : function() {
							$(this).dialog('close');
						}
					},
					close: function() {}
		    });
			
			
			$('#newTagInput').autocomplete('/' + db_name + '/_design/tags/_view/by_tag_grouped', {
				multiple: false,
				minChars: 1,
				max: 300,
				selectFirst: false,
				dataType: "json",
				extraParams: {
					startkey: function() {return '"' + $('#tagsearch').val() + '"'},
					group: 'true'
				},
				parse: function(data) {
					var arr = new Array();
					for (var i=0; i < data.rows.length;i++) {
						arr[i] = {
							data: data.rows[i],
							value: data.rows[i].key,
							result: data.rows[i].key
						};
					}
					return arr;
				},
				formatItem: function(item) {
					return item.key + " (" + item.value + ")" ;
				}

			});
			
			

           query_vars = $.parseQuery();
		   if (!query_vars.name) {
		      jQuery.each(query_vars, function(name, value) {
				  if (value == 'undefined') query_vars.name = name;
			  });
		   }
		   
           $('#c_name').text(query_vars.name);

           $('#tabs').tabs();

           

           $.getJSON("/" + db_name + "/" + query_vars.name + "/?callback=?", function(data){
                 conversation = data;
                 $('#c_description').text(data.description);
                 var d = Date.parse(data.media.startdate);
                 $('#calendar').datepicker({ defaultDate: d, minDate: d, maxDate: d });
                 $('.ui-datepicker').css('width', '13em');
                 $('.ui-datepicker-next span').hide();
                 $('.ui-datepicker-prev span').hide();
				 $('.futon').attr('href', '/_utils/document.html?' + db_name + '/' + query_vars.name);
				 
				 
                 player = createPlayer(data.media, findRequestedStartTime(), finishLoadingAudio);
				 
				 if (data._attachments)
					parseAttachments(data._attachments);
				 // create the scrubber
				 
				$("#scrubber").slider({
						range: false,
						min: 0,
						max: conversation.media.mediaLength,
						value: 0,
						start: function(event, ui) {
							disableScrubberUpdates = true;
						},
						stop:  function(event, ui) {
							var time = $('#scrubber').slider('option', 'value');
							player.seek(time);
							disableScrubberUpdates = false;
						}
				});
				updateTagList();
				callTwitter();
				

           });

			$('#addTagButton').bind('click', function() {
				showAddTagDialog();
			});
        });
		
		
		function showAddTagDialog() {
				var currTime = $("#scrubber").slider('option', 'value');
				$('#newTagTime').val(currTime);
				$('#newTagInput').val("");
				$('#newTagDescription').val("");
				$('#newTagDialog').dialog("open");
				$('#newTagDialog').dialog("open");	
		}
		
		function convertTweet(tweetId) {
			var tweet = twitter_id_to_tweet[tweetId];
			var mediaOffset = findMediaOffsetOfTweet(tweet);
			var tagName = findTweetTag(tweet);
			var tagDescription = tweet.text;

			addTag(tagName, mediaOffset, tagDescription )
		}

		function callTwitter() {
			var user = $.cookie('twitter');
			if (user == null || "" == user) return;
			console.log('twitter user: ' + user);
			var twitter_url = buildTwitterUrl(user);
			console.log('twitter url: ' + twitter_url);
			//$.getJSON("twitter.json?callback=?", function(data){
			$.getJSON(buildTwitterUrl(user), function(data){
				var tags = {};
				tags.conversation_id = query_vars.name;
				tags.rows = [];
				jQuery.each(data.results, function(i, val) {
					var row = createTwitterTag(this);
					if (row != null) {
						tags.rows.push(row);
						twitter_id_to_tweet[row.twitterId] = this;
					}
				});
				tags.rows.reverse(); // twitter is ordered newest back.
				// attach the template
				$("#external_tags_table").setTemplateElement("external_tags_table_template");
				
				
				// process the template
				$("#external_tags_table").processTemplate(tags);
				updatePlayhead();
			
			});
		}
		
		function buildTwitterUrl(user) {
						
			var base = "http://search.twitter.com/search.json?rpp=30&";
			var since = Date.parse(conversation.media.startdate).toString('yyyy-MM-dd');
			var today = new Date().toString('yyyy-MM-dd');
			if (since != today) {
				
				base = base + "since=" + since;
				base = base	+ "&until=" + since;
			}
			base = base + "&q=from%3A" + user + "&callback=?";
			return base;
		}
		
		
		
		function createTwitterTag(tweet) {
			if (!isTweetInConversationDate(tweet)) return null;
			var tag = {};
			tag.mediaOffset = findMediaOffsetOfTweet(tweet);
			tag.tag = findTweetTag(tweet);
			tag.description = tweet.text;
			tag.twitterId = tweet.id;
			return tag;
		}
		
		function findTweetTag(tweet) {
			var hash = tweet.text.match(/(^|\s+)#([a-zA-Z0-9_-]+)/i);
			if (hash != null) {
				return hash[2];
			}
			return 'tag';
		}
		
		function findMediaOffsetOfTweet(tweet) {
			var tweet_date = new Date(tweet.created_at).getTime();
			//console.log("tweet date: " + tweet_date);
			var c_start = Date.parse(conversation.media.startdate).getTime();
			
			return Math.round((tweet_date - c_start) / 1000);
			
		}
		
		
		function isTweetInConversationDate(tweet) {
			var c_start_date = Date.parse(conversation.media.startdate);
			var c_start = c_start_date.getTime();
			var tweet_date = new Date(tweet.created_at).getTime();
			var c_end = c_start_date.add(conversation.media.mediaLength).seconds().getTime();
			return ((tweet_date >= c_start) && (tweet_date <= c_end));
		}
		
		
		function updateTagList() {
		   $("#tags_table").empty();
           $.getJSON("/" + db_name + "/_design/tags/_view/by_conversation_ordered?startkey=[%22"+ query_vars.name +"%22]&endkey=[%22"+ query_vars.name +"%22,{}]&callback=?", function(data){
				conversation_tags = data;
				data.conversation_id = query_vars.name;
				// attach the template
				$("#tags_table").setTemplateElement("tags_table_template");
				
				// process the template
				$("#tags_table").processTemplate(data);
				windowResize();
				updatePlayhead();
				jQuery.each(data.rows, function(i, val) {
					 tag_id_to_row[this.id] = val;
					 var mediaEndOffset = this.value.mediaOffset + this.value.duration
					 $("#mt-"+ this.id).slider({
						range: true,
						min: 0,
						max: conversation.media.mediaLength,
						values: [this.value.mediaOffset, mediaEndOffset],
						change: function(event, ui) {
						        var id = this.id.substring(3);
								//console.log("moved: " + id + " to " + ui.values[0] + " " + ui.values[1]);
						        var tag = tag_id_to_row[id].value;
								var duration = ui.values[1] - ui.values[0];
								tag.duration = duration;
								tag.mediaOffset = parseInt(ui.values[0]) ;
								tag.start =  Date.parse(conversation.media.startdate).add({seconds: tag.mediaOffset}).toString('yyyy-MM-ddTHH:mm:ssZ');
								requestTagChange(id);
							   //console.log("moved: " + this.id + " to " + ui.values[0]);
						}
					});
					$(".ui-slider").bind("click", function() {
						alert('click');
					});
				}); // end of each
				$('.tag_description').editable(function(value, settings) { 
					 var tag_id = this.id.substring(5);
					 var tag = tag_id_to_row[tag_id].value;
					 tag.description = value;		
					 requestTagChange(tag_id);
					 return(value);
				  }, { 
					 type    : 'textarea',
					 submit  : 'OK',
				 });
				 
				 $('td.top').each(function() {
					$(this).parent().css('background-color', '#E2E2E2').children('td').eq(1).children('div').eq(0).css({'background-color':'#E2E2E2', "border":"0px solid #F2F2F2","background":"none"});
				 });
				 $('td[parent^=row]').each(function() {
					$(this).css('padding-left', '20px');
				 });
				 
				 
				$('.ui-slider-horizontal').css('border','1px solid FFFFFF');
				//$('#tags_table tr:even').css('background-color', '#E2E2E2');
				//$('#tags_table .tagdiv:even').css({'background-color':'#E2E2E2', "border":"0px solid #F2F2F2","background":"none"});
           });		
		}
		
		function requestTagChange(tagId) {
			$(document).stopTime(tagId);
			$(document).oneTime(1000, tagId, function() {
			      //console.log('tagId: ' + tagId);
			      putTag(tagId);
			});
		}
		
		function putTag(tagId) {
			var tag = tag_id_to_row[tagId].value;
			var data = JSON.stringify(tag);
			$.ajax({
			   type: "PUT",
			   url: "/" + db_name + "/" + tag._id,
			   data: data,
			   processData: false,
			   dataType: "json",
			   success: function(msg){
					tag._rev = msg.rev;
			   }
			 });
		}
		
		var lastTagTime;
		
		function playTag(time) {
			lastTagTime = time;
			player.seek(time);
			return false;
		}
		
		function playLastTag() {
			if (lastTagTime) {
				playTag(lastTagTime);
			}
		}
		
		
		function addTag(tagName, mediaOffset, tagDescription ) {
			var tag = {};
			tag.tag = tagName;
			tag.conversation = query_vars.name;
			tag.duration = 20;
			tag.mediaOffset = parseInt(mediaOffset) ;
			tag.type = 'tag';
			tag.start =  Date.parse(conversation.media.startdate).add({seconds: mediaOffset}).toString('yyyy-MM-ddTHH:mm:ssZ');
			if (tagDescription != null) tag.description = tagDescription;
			var data = JSON.stringify(tag);
			$.ajax({
			   type: "POST",
			   url: "/" + db_name + "/",
			   data: data,
			   success: function(msg){
				 updateTagList();
			   }
			 });

		}
		
		function deleteTag(tagId) {
		    tag_to_remove = tagId;
		    $('#removeTagDialog').dialog('open');
			
			//
			return false;
		}
		
    </script>
  </head>
  <body class="primary-4">
	<div id="header"></div>
  
    <div id="content" data-corner="left right 20px">
        <div id="calendar_bounds">
            <div id='calendar'></div>
			<a class="futon" title="View in Futon"><img src="images/script.gif" border="0" /></a>
        </div>
        
        <div id="conversation">
            <div id="conversation_details">
                <div class="font-2"><span id="c_name"></span></div>
                <span id="c_description"></span>
            </div>
             <div id="fms"></div>
            <div id="loading" style="position: relative; z-index: 30; top: -55px; left: 200px;">
                    <img src="images/indicator.gif" /> <span style="">Loading Audio...</span>
            </div>
             <div id="tabs" style="margin-top: 42px;">
                 <ul>
                     <li><a href="#tags-tab">Tags</a></li>
                     <li><a href="#attendees-tab">Attendees</a></li>
                     <li><a href="#images-tab">Images</a></li>
                     <li><a href="#map-tab">Map</a></li>
                 </ul>
                 <div id="tags-tab">
				     <table class="tagtable" >
					    <thead>
							<tr class="scrubber_row">
								<td ><button id="addTagButton">Add</button></td>
								<td><div id="scrubber" class="tagdiv"></div></td>
							</tr>
						</thead>
						<tbody id="tags_table"></tbody>
						<tfoot id="external_tags_table"></tfoot>
					</table>
                    <div id="playhead" ></div>
                 </div>
                 <div id="attendees-tab">
                     <div id="attendees"></div>
                 </div>
                 <div id="images-tab">
                     <div id="images_table" ></div>
                 </div>
                 <div id="map-tab">
                     <div id="map"></div>
                 </div>
             </div>



        </div>
    </div>

	<div id="newTagDialog" style="display: none;" title="Add A Tag...">
			<label for="newTagInput">Tag</label>
			<input id="newTagInput" type="text" name="newTagInput" />
			<label for="newTagDescription">Description</label>
			<textarea name="newTagDescription" id="newTagDescription"></textarea>
			<input id="newTagTime" type="hidden" name="newTagTime" />
	</div>

	<div id="removeTagDialog" style="display: none;" title="Remove Tag...">
		Are you sure you want to remove this tag?
	</div>


    <!-- Templates content (Valid XHTML 1.1) -->
    <p style="display: none;"><textarea id="tags_table_template" rows="0" cols="0">
					
                    {#foreach $T.rows as row}
                    <tr class="tagrow">
                        <td class="taginfo {#if $T.row.value.parent ==null}top{#/if}" id="row-{$T.row.id}" {#if $T.row.value.parent !=null}parent="row-{$T.row.value.parent}"{#/if} >
						  <a href="conversation.html?name={$T.conversation_id}&time={$T.row.value.mediaOffset}" >{$T.row.value.tag}</a>						  
                          <a href="#" onclick="return playTag({$T.row.value.mediaOffset});"><img src="images/play.png"   title="Play." alt="Play."      onmouseover="this.src='images/play-dark.png'"  onmouseout="this.src='images/play.png'"/></a>
                          <a href="tag.html?tag={$T.row.value.tag}"><img src="images/tag-light.png"   title="Show {$T.row.value.tag} tags from all conversations." alt="Show {$T.row.value.tag} tags from all conversations."      onmouseover="this.src='images/tag.png'"  onmouseout="this.src='images/tag-light.png'"/></a>
						  <a href="#" onclick="return deleteTag('{$T.row.id}');"><img src="images/cross-light.png"   title="Delete this tag instance." alt="Delete this tag instance."      onmouseover="this.src='images/cross.png'"  onmouseout="this.src='images/cross-light.png'"/></a>
						  <a href="{'/_utils/document.html?' + db_name + '/' + $T.row.id}" title="View in Futon"><img src="images/script.gif" border="0" /></a>
						  {#if $T.row.value.description !=null}<div class="tag_description" id="desc-{$T.row.id}">{$T.row.value.description}</div>{#/if}
						  {#if $T.row.value.icons}
							<div class="tag_icons">
						      {#foreach $T.row.value.icons as icon}
							     <img src="images/fm/{$T.icon}.png" title="{$T.icon}" />
						      {#/for}
						     </div>
						   {#/if}
						   {#if $T.row.value.attendees}
						     <ul class="tag_attendees">
							  {#foreach $T.row.value.attendees as attendee}
							     {#if $T.attendee.id}
							     <li>
								   <a href="person.html?name={$T.attendee.id}">{$T.attendee.id}</a>
								 </li>
						      {#/for}
								 {#/if}
			   
							 </ul>
						   {#/if}
                        </td>
                        <td class="tagbar"><div id="mt-{$T.row.id}" class="tagdiv"></div></td>
                    </tr>
                    {#/for}

    </textarea></p>

	<!----------------- START ---------------->
    <p style="display: none;"><textarea id="images_table_template" rows="0" cols="0">	    <ul class="gallery">
            {#foreach $T.images as image}
                <li><img src="{$T.image.url}" title="{$T.image.name}" alt="{$T.image.name}" width="800"/></li>
            {#/for}
        </ul>
    </textarea></p>
	<!----------------- END ---------------->
	
	<!----------------- START ---------------->
    <p style="display: none;"><textarea id="external_tags_table_template" rows="0" cols="0">
			<tr>
			   <td colspan="2"> <b>Twitter Feed.</b> The items below are not seen by others. </td>
			</tr>
			{#foreach $T.rows as row}
                    <tr class="tagrowExternal" ">
                        <td class="taginfo">
						  <a href="conversation.html?name={$T.conversation_id}&time={$T.row.mediaOffset}" >{$T.row.tag}</a>		
						  <a href="#" onclick="return playTag({$T.row.mediaOffset});"><img src="images/play.png"   title="Play." alt="Play."      onmouseover="this.src='images/play-dark.png'"  onmouseout="this.src='images/play.png'"/></a>
                          <a href="tag.html?tag={$T.row.tag}"><img src="images/tag-light.png"   title="Show {$T.row.tag} tags from all conversations." alt="Show {$T.row.tag} tags from all conversations."      onmouseover="this.src='images/tag.png'"  onmouseout="this.src='images/tag-light.png'"/></a>
						<a href="#" onclick="return convertTweet('{$T.row.twitterId}');"><img src="images/wand.gif"   title="Convert and save this tag." alt="Convert and save this tag."  onmouseover="this.src='images/wand.gif'"  onmouseout="this.src='images/wand.gif'"/></a>

						  
						{#if $T.row.description !=null}<div class="tag_description" id="desc-{$T.row.id}">{$T.row.description}</div>{#/if}						  
                        </td>
                        <td class="tagbar"><div class="tagdivExternal"></div></td>
                    </tr>
             {#/for}
    </textarea></p>
	<!----------------- END ---------------->
    <p style="display: none;"><textarea id="map_template" rows="0" cols="0">
         <div id="freemind" >
            <button onclick="inspectApplet()">Play Selected</button> <span>This is the original upload. It does not reflect the changes made after upload.</span>
            <applet name="freemindApplet" code="freemind.main.FreeMindApplet.class" archive="scripts/freemind/freemindbrowser.jar" width="100%" height="100%" >
                <param name="type" value="application/x-java-applet;version=1.4"/>
                <param name="scriptable" value="true"/>
                <param name="modes" value="freemind.modes.browsemode.BrowseMode"/>
                <param name="browsemode_initial_map" value="{$T.url}"/>
                <param name="initial_mode" value="Browse"/>
                <param name="selection_method" value="selection_method_direct"/>
            </applet>
        </div>
    </textarea></p>
    <!-- End Of templates-->

  </body>
</html>
